/*
 * Copyright (C) 2009 Show SMS open source project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bydavy.android.showsms.util;

//~--- non-JDK imports --------------------------------------------------------

import android.content.Context;

import android.database.Cursor;

import android.net.Uri;

import android.util.Log;

import com.bydavy.android.showsms.model.ShortMessage;

//~--- JDK imports ------------------------------------------------------------

import java.util.Vector;

//~--- classes ----------------------------------------------------------------

public class ShortMessageInfos {
    //~--- static fields ------------------------------------------------------

    public static final Uri SMS_CONTENT_URI        = Uri.parse("content://sms");
    public static final Uri SMS_INBOX_CONTENT_URI  = Uri.withAppendedPath(SMS_CONTENT_URI, "inbox");
    public static final Uri SMS_OUTBOX_CONTENT_URI = Uri.withAppendedPath(SMS_CONTENT_URI, "outbox");
    public static final Uri MMS_SMS_CONTENT_URI    = Uri.parse("content://mms-sms/");
    public static final Uri THREAD_ID_CONTENT_URI  = Uri.withAppendedPath(MMS_SMS_CONTENT_URI, "threadID");

    //~--- constructors -------------------------------------------------------

    private ShortMessageInfos() {}

    //~--- methods ------------------------------------------------------------

    /**
     * Find message id from his thread id and his body in the database
     *
     * @param threadId message thread id of the message to find
     * @param body message body of the message to find
     * @param context application context
     *
     * @return message id from the database, or ShortMessage.NO_ID_FOUNDED if the message doesn't exist in hte database
     */
    public static long findId(long threadId, String body, Context context) {
        long id             = 0;
        String[] projection = new String[] { "_id" };
        String selection    = new String("thread_id=" + threadId);
        String order        = new String("date desc");
        Cursor cursor       = context.getContentResolver().query(SMS_INBOX_CONTENT_URI, projection, selection, null,
                                  order);

        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    int idColumn = cursor.getColumnIndex("_id");

                    id = cursor.getLong(idColumn);
                }
            } finally {
                cursor.close();
            }
        }

        AppLog.v("Found id message: " + id);

        return id;
    }

    public static Vector<ShortMessage> findConversation(Context context, long threadId, long idExcludedMsg) {
        Vector<ShortMessage> messages = new Vector<ShortMessage>();
        long id;
        String body;
        long date;

        String[] projection = new String[] { "_id", "body", "date" };
        String selection    = new String("thread_id=" + threadId);

        if (idExcludedMsg != 0L) {
            selection = selection.concat(" and _id<>" + idExcludedMsg);
        }

        String order  = new String("date desc");
        Cursor cursor = context.getContentResolver().query(SMS_INBOX_CONTENT_URI, projection, selection, null, order);

        if (cursor != null) {
            try {
                while (cursor.moveToNext()) {
                    int idColumn = cursor.getColumnIndex("_id");
                    int idBody   = cursor.getColumnIndex("body");
                    int idDate   = cursor.getColumnIndex("date");

                    id   = cursor.getLong(idColumn);
                    body = cursor.getString(idBody);
                    date = cursor.getLong(idDate);

                    ShortMessage m = new ShortMessage(id, body, date);

                    messages.add(m);
                }

            } finally {
                cursor.close();
            }
        }

        Log.e("Show SMS", " Nb=" + messages.size());

        return messages;
    }

    /**
     * Find message thread id from sender phoneNumber in the database
     *
     * @param context application context
     * @param phoneNumber sender message phone number
     *
     * @return thread id from the database, or ShortMessage.NO_THREAD_ID_FOUNDED if the message doesn't exist in hte database
     */
    public static long findThreadId(Context context, String phoneNumber) {
        String THREAD_RECIPIENT_QUERY = "recipient";
        Uri.Builder uriBuilder        = THREAD_ID_CONTENT_URI.buildUpon();

        uriBuilder.appendQueryParameter(THREAD_RECIPIENT_QUERY, phoneNumber);

        String[] selection = new String[] { "_id" };
        long threadId      = 0;
        Cursor cursor      = context.getContentResolver().query(uriBuilder.build(), selection, null, null, null);

        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    threadId = cursor.getLong(0);
                }
            } finally {
                cursor.close();
            }
        }

        AppLog.v("Found thread id: " + threadId);

        return threadId;
    }
}
